<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\helpers\traits\ImageUpload;
use app\helpers\traits\SearchDataForModel;
use app\model\Admin;
use app\model\AuthRule;
use think\exception\ValidateException;
use think\Request;

class Menu extends BaseController
{
    use SearchDataForModel,ImageUpload;

    /**
     * @User: 刘海龙
     * @Date: 2021/2/26
     * @Time: 9:26
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 菜单查询
     */
    public function menuInfo()
    {

        $data = AuthRule::select();

        $name = $this->request->param('name', '');
        $type = $this->request->param('type', 'list');

        if (!empty($name) && $type == 'child') {
            $top = AuthRule::where('parent_id', 0)
                ->where('title', 'like', '%' . $name . '%')
                ->order('sort', 'asc')->select()->toArray();
        }
        if (!empty($top) && $type == 'child') {
            $res       = [];
            $parent_id = [];
            foreach ($top as $key => $val) {
                $res[]              = $val;
                $res[$key]['child'] = AuthRule::sortMenu($data, $val['id']);
                $parent_id[]        = $val['id'];
            }
            empty($name) ?:
                $down = AuthRule::whereNotIn('parent_id', $parent_id)
                    ->where('name', 'like', '%' . $name . '%')
                    ->order('sort', 'asc')->where('parent_id', '<>', 0)
                    ->select()->toArray();
            empty($down) ?: $res = array_merge($res, $down);
        } elseif (empty($name) && $type == 'child') {
            $data = $this->search(new AuthRule(), [], $perPage = 200);
            $res  = AuthRule::sortMenu($data, 0);
        } else {
            $res = $this->search(new AuthRule(), [], $perPage = 200);
        }
        return $this->response($res);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/2/26
     * @Time: 9:27
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 新增菜单and编辑
     */
    public function MenuSave()
    {
        $id = $this->request->param('id', 0);

        try {
            $validator = $this->validate($this->request->param(),
                \app\validate\Menu::rules($id),
                \app\validate\Menu::msg());
            if ($validator) {
                $data           = $this->request->only([
                    'name',
                    'title',
                    'parent_id',
                    'sort',
                    'icon',
                    'type',
                    'remark',
                    'is_open',
                    'level',
                    'icon_activation',
                ]);
                $data['is_open'] = $this->request->param('status', true) ? 1 : 0;
                $parent_id      = $this->request->param('parent_id', 0);
                if (intval($parent_id) === 0) {
                    $data['level'] = 0;
                } else {
                    $data['level'] = AuthRule::find($parent_id)->level + 1;
                }
                if (intval($id) === 0) {
                    if (intval($parent_id) != 0) {
                        if (AuthRule::find($parent_id)->level === 2) {
                            return $this->response(501, "菜单只能添加3级");
                        }
                    }
                    AuthRule::create($data);
                } else {
                    $menu = AuthRule::find($id);
                    $menu->save($data);
                }
                return $this->response();
            }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->response(403, $e->getError());
        }
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/2/26
     * @Time: 9:27
     * @return \think\response\Json
     * 获取菜单类别
     */
    public function MenuType()
    {
        $content = [
            [
                'id'   => AuthRule::TYPE_ONE,
                'name' => AuthRule::$is_type[AuthRule::TYPE_ONE],
            ],
            [
                'id'   => AuthRule::TYPE_TWO,
                'name' => AuthRule::$is_type[AuthRule::TYPE_TWO],

            ],
        ];
        return $this->response($content);
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/7/22
     * @Time: 18:02
     * @return \think\response\Json
     * 删除菜单
     */
    public function MenuDel($id)
    {
        $parent_id = AuthRule::where('parent_id', $id)->count();
        if ($parent_id > 0) {
            return $this->response(501, '删除失败,此菜单存在子菜单');
        };
        AuthRule::destroy($id);
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/7/22
     * @Time: 18:02
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 添加子菜单
     */
    public function childSave()
    {

        $id = $this->request->param('id');
        try {
            $validator = $this->validate($this->request->param(),
                \app\validate\Menu::rules($id),
                \app\validate\Menu::msg());

            if ($validator) {
                $data      = $this->request->only([
                    'name',
                    'parent_id',
                    'sort',
                    'icon',
                    'title',
                    'type',
                    'remark',
                    'is_open',
                    'level',
                    'icon_activation',
                ]);
                $parent_id = $this->request->param('parent_id', 0);
                if (intval($parent_id) === 0) {
                    $data['level'] = 0;
                } else {
                    $data['level'] = AuthRule::find($parent_id)->level + 1;
                }
                $data['status'] = $this->request->param('status', true) ? 1 : 0;
                if (intval($id) === 0) {
                    if (intval($parent_id) != 0) {
                        if (AuthRule::find($parent_id)->level === 2) {
                            return $this->response(501, "菜单只能添加3级");
                        }
                    }
                }
                AuthRule::create($data);
                return $this->response();
            }
        } catch (ValidateException $exception) {
            return $this->response(403, $exception->getError());
        }


    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/7/22
     * @Time: 18:02
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 获取菜单树
     */
    public function selectMenuTree($id)
    {
        $data = $this->search(new AuthRule(), [], $perPage = 200);
        foreach ($data as $key => $v) {
            if ($v['id'] == $id) {
                $data[$key]['disabled'] = true;
            }
        }
        $res = AuthRule::sortMenu($data, 0);

        return $this->response($res);
    }
    /**
     * @User: 刘海龙
     * @Date: 2021/7/22
     * @Time: 17:19
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取用户菜单权限
     */
    public function menuPermission(){
        $user = Admin::find($this->request->uid);
        // 检查用户权限
        $role_ids = array_column($user->roles()->select()->toArray(),
            'rules');//获取该用户所属角色rules
        if (in_array('*', $role_ids)) {
            $data = AuthRule::where('is_open', AuthRule::OPEN_ONE)->select()
                ->toArray();
        } else {
            $data = AuthRule::where('id', 'in', implode(',', $role_ids))
                ->where('is_open', AuthRule::OPEN_ONE)
                ->select()->toArray();
        }

        $res = AuthRule::sortMenu($data);
        return $this->response($res);
    }
}
